<?php
// +----------------------------------------------------------------------
// | 用户权益模块业务逻辑
// +----------------------------------------------------------------------
// | Author: myh
// +----------------------------------------------------------------------
namespace app\admin\service;

use app\common\model\UserPrivilegeModel;

class UsePrivilegeService{

    public static $cache_user_privilege_list_key = 'user_privilege_list';

    /**
     * 新增
     * @param  array  $data  新增的数据
     * @return int
     */
    public static function save($data){
        $model = new UserPrivilegeModel;
        $model->save($data);
        //清空缓存
        cache(self::$cache_user_privilege_list_key, null);
        return success($model->id);
    }

    /**
     * 更新
     * @param  array  $data 更新的数据
     * @return int
     */
    public static function update($data){
        $model = UserPrivilegeModel::find($data['id']);
        if(!$model){
            return failure(config('error.er15')['code'],config('error.er15')['msg']);
        }
        //清空缓存
        cache(self::$cache_user_privilege_list_key, null);
        return success($model->save($data));
    }

    /**
     * 删除
     * @param  string  $ids  需要删除数据的id
     */
    public static function destroy($ids){
        if(!empty($ids)){
            //清空缓存
            cache(self::$cache_user_privilege_list_key, null);
            UserPrivilegeModel::destroy(explode(',',$ids));
        }
    }

    /**
     * 列表
     * @return array
     */
    public static function list(){
        if(cache(self::$cache_user_privilege_list_key)){
            return success(cache(self::$cache_user_privilege_list_key));
        }

        $list = UserPrivilegeModel::order('growth_value','asc')->select();
        if(!empty($list)){
            //永久缓存
            cache(self::$cache_user_privilege_list_key, $list, 0);
        }
        return success($list);
    }

    /**
     * 根据ID获取名称
     * @param  string  $id ID
     * @return string
     */
    public static function getPrivilegeNameById($id){
        $list = self::list();
        $privilegeName = '';
        foreach($list as $v){
            if($v['id'] == $id){
                $privilegeName = $v['privilege_name'];
                break;
            }
        }
        return $privilegeName;
    }
}